from django.shortcuts import render
from django.views import View

from apps.verifications.constants import SMS_CODE_EXPIRE_TIME, IMAGE_CODE_EXPIRE_TIME
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection

from django.http import HttpResponse, JsonResponse
# Create your views here.
from libs.ronglianyun.SendTemplateSMS import CCP
from utils.response_code import RETCODE
import logging

logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, IMAGE_CODE_EXPIRE_TIME, text)

        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):
    def get(self, request, mobile):
        image_code = request.GET.get('image_code')
        image_code_id = request.GET.get('image_code_id')
        if not all([mobile, image_code_id, image_code]):
            return JsonResponse({'code': '0', 'errormsg': '参数不齐'})

        try:
            redis_conn = get_redis_connection('code')
            redis_code = redis_conn.get('img_%s' % image_code_id)

            if redis_code is None:
                return JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '验证码过期'})

            # 删除图片验证码，
            # 防止用户再次比对
            # 清除无用的数据，释放内存
            redis_conn.delete('img_%s' % image_code_id)
        except Exception as e:
            logger(e)
            return JsonResponse({'code':RETCODE.IMAGECODEERR,'errormsg':'数据库redis有异常'})

        send_flag = redis_conn.get('send_flag_%s'%mobile)
        if send_flag:
            return JsonResponse({'code':RETCODE.SMSCODERR,'errmsg':'操作太频繁'})

        if redis_code.decode().lower() != image_code.lower():
            return JsonResponse({'code': RETCODE.SMSCODERR, 'errormsg': '短信验证码错误'})

        from random import randint
        sms_code = '%06d' % randint(0, 999999)

        pipe = redis_conn.pipeline()

        pipe.setex('sms%s' % mobile, SMS_CODE_EXPIRE_TIME, sms_code)
        pipe.setex('send_flag_%s'%mobile,60,1)

        pipe.execute()

        # CCP().send_template_sms(mobile, [sms_code, SMS_CODE_EXPIRE_TIME / 60], 1)
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code(mobile,sms_code,SMS_CODE_EXPIRE_TIME/60)

        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        # return HttpResponse()
